import os
import json
import re
from collections import Counter

# from PIL import Image
# import numpy as np
# from typing import List, Union, Optional

# def stitch_images(
#     image_paths: List[str],
#     output_path: Optional[str] = None,
#     rows: Optional[int] = None,
#     cols: Optional[int] = None,
#     direction: str = 'horizontal',
#     spacing: int = 0,
#     background_color: tuple = (255, 255, 255)
# ) -> Image.Image:
#     """
#     将多个图片拼接成一个大图片
    
#     Args:
#         image_paths: 图片路径列表
#         output_path: 输出图片保存路径，如果为None则不保存
#         rows: 行数，如果为None则自动计算
#         cols: 列数，如果为None则自动计算
#         direction: 拼接方向，'horizontal'水平或'vertical'垂直
#         spacing: 图片间距，默认为0
#         background_color: 背景颜色，默认为白色
    
#     Returns:
#         PIL.Image.Image: 拼接后的大图片
#     """
#     if not image_paths:
#         raise ValueError("图片列表不能为空")
    
#     # 读取所有图片
#     images = []
#     for path in image_paths:
#         if not os.path.exists(path):
#             raise FileNotFoundError(f"图片不存在: {path}")
#         img = Image.open(path)
#         images.append(img)
    
#     # 计算行列数
#     num_images = len(images)
#     if rows is None and cols is None:
#         # 自动计算行列数，尽量接近正方形
#         if direction == 'horizontal':
#             cols = int(np.ceil(np.sqrt(num_images)))
#             rows = int(np.ceil(num_images / cols))
#         else:
#             rows = int(np.ceil(np.sqrt(num_images)))
#             cols = int(np.ceil(num_images / rows))
#     elif rows is None:
#         rows = int(np.ceil(num_images / cols))
#     elif cols is None:
#         cols = int(np.ceil(num_images / rows))
    
#     # 检查行列数是否足够
#     if rows * cols < num_images:
#         raise ValueError(f"行列数不足: {rows}x{cols} 只能容纳 {rows*cols} 张图片，但有 {num_images} 张图片")
    
#     # 获取所有图片的尺寸
#     widths = [img.width for img in images]
#     heights = [img.height for img in images]
    
#     # 计算每行每列的最大尺寸
#     if direction == 'horizontal':
#         # 水平拼接：每列宽度相同，每行高度相同
#         col_widths = [max(widths[i::cols]) for i in range(cols)]
#         row_heights = [max(heights[i*cols:min((i+1)*cols, num_images)]) for i in range(rows)]
#     else:
#         # 垂直拼接：每行高度相同，每列宽度相同
#         row_heights = [max(heights[i::rows]) for i in range(rows)]
#         col_widths = [max(widths[i*rows:min((i+1)*rows, num_images)]) for i in range(cols)]
    
#     # 计算大图片的总尺寸
#     total_width = sum(col_widths) + spacing * (cols - 1)
#     total_height = sum(row_heights) + spacing * (rows - 1)
    
#     # 创建大画布
#     stitched_image = Image.new('RGB', (total_width, total_height), background_color)
    
#     # 拼接图片
#     x_offset, y_offset = 0, 0
#     for i, img in enumerate(images):
#         if direction == 'horizontal':
#             row_idx = i // cols
#             col_idx = i % cols
#             cell_width = col_widths[col_idx]
#             cell_height = row_heights[row_idx]
#         else:
#             row_idx = i % rows
#             col_idx = i // rows
#             cell_width = col_widths[col_idx]
#             cell_height = row_heights[row_idx]
        
#         # 计算图片在单元格中的位置（居中）
#         x_center = x_offset + (cell_width - img.width) // 2
#         y_center = y_offset + (cell_height - img.height) // 2
        
#         # 粘贴图片
#         stitched_image.paste(img, (x_center, y_center))
        
#         # 更新偏移量
#         if direction == 'horizontal':
#             x_offset += cell_width + spacing
#             if (i + 1) % cols == 0:  # 换行
#                 x_offset = 0
#                 y_offset += row_heights[row_idx] + spacing
#         else:
#             y_offset += cell_height + spacing
#             if (i + 1) % rows == 0:  # 换列
#                 y_offset = 0
#                 x_offset += cell_width + spacing
    
#     # 保存图片
#     if output_path:
#         stitched_image.save(output_path)
#         print(f"图片已保存到: {output_path}")
    
#     return stitched_image



def read_json_file(file_path):
    """
    第一步：读取JSON文件
    Args:
        file_path (str): JSON文件路径
    Returns:
        list: 读取到的数据列表
    """
    try:
        with open(file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
            print(f"成功读取文件: {file_path}")
            return data
    except FileNotFoundError:
        print(f"错误：文件 {file_path} 不存在")
        return None
    except json.JSONDecodeError:
        print(f"错误：文件 {file_path} 不是有效的JSON格式")
        return None
    except Exception as e:
        print(f"读取文件时发生错误: {e}")
        return None


def replace_underscore_in_dishIngredient(data):
    """
    第二步：替换dishIngredient字段中的"_"为","
    Args:
        data (list): 包含字典的列表数据
    Returns:
        list: 处理后的数据
    """
    if not data or not isinstance(data, list):
        print("\033[91m错误：数据格式不正确，应为列表\033[0m")
        return data
    
    processed_count = 0
    for item in data:
        if isinstance(item, dict) and 'dishIngredient' in item:
            # 替换dishIngredient字段中的"_"为","
            if isinstance(item['dishIngredient'], str):
                item['dishIngredient'] = item['dishIngredient'].replace('_', ', ')
                processed_count += 1
    
    print(f"成功处理了 {processed_count} 个dishIngredient字段")
    return data, processed_count


def convert_format(data):
    """
    步骤2：转换格式（数组格式转换为每行一个JSON对象）
    """
    if not data:
        return None
    
    converted_data = []
    for item in data:
        # 将每个对象转换为JSON字符串
        json_line = json.dumps(item, ensure_ascii=False)
        converted_data.append(json_line)
    
    print("格式转换完成")
    return converted_data

def write_json_file_bydump(data, output_file_path):
    """
    第三步：将处理后的数据写入新的JSON文件
    Args:
        data (list): 要写入的数据
        output_file_path (str): 输出文件路径
    """
    try:
        # 确保输出目录存在
        os.makedirs(os.path.dirname(output_file_path), exist_ok=True)
        
        with open(output_file_path, 'w', encoding='utf-8') as file:
            json.dump(data, file, ensure_ascii=False, indent=4)
        print(f"成功写入文件: {output_file_path}")
        return True
    except Exception as e:
        print(f"写入文件时发生错误: {e}")
        return False

def write_json_file(data, output_file_path):
    """
    步骤3：将转换后的数据写入JSON文件
    """
    if not data:
        print("没有数据可写入")
        return False
    try:
        # 确保输出目录存在
        os.makedirs(os.path.dirname(output_file_path), exist_ok=True)

        with open(output_file_path, 'w', encoding='utf-8') as file:
            # 每行写入一个JSON对象
            for line in data:
                file.write(line + '\n')
        print(f"成功写入文件：{output_file_path}")
        return True
    except Exception as e:
        print(f"写入文件时发生错误：{e}")
        return False


def process_single_json_file(input_file, output_file=None):
    """
    处理单个JSON文件的完整流程
    Args:
        input_file (str): 输入文件路径
        output_file (str): 输出文件路径，如果为None则自动生成
    """
    if output_file is None:
        # 自动生成输出文件名：在原文件名后添加_processed
        base_name = os.path.splitext(input_file)[0]
        output_file = f"{base_name}_processed.json"
    
    # 第一步：读取文件
    data = read_json_file(input_file)
    if data is None:
        return False
    
    # 第二步：替换字段
    processed_data, processed_count = replace_underscore_in_dishIngredient(data)

    # processed_data_format = convert_format(processed_data)
    processed_data_format = processed_data
    
    # 第三步：写入文件
    # success = write_json_file(processed_data_format, output_file)
    success = write_json_file_bydump(processed_data_format, output_file)
    return success, len(data), processed_count

def process_multiple_json_files(input_dir, output_dir=None):
    """
    批量处理目录下的所有JSON文件
    Args:
        input_dir (str): 输入目录路径
        output_dir (str): 输出目录路径，如果为None则使用输入目录
    """
    if output_dir is None:
        output_dir = input_dir
    
    # 获取目录下所有JSON文件
    json_files = [f for f in os.listdir(input_dir) if f.endswith('.json')]
    
    if not json_files:
        print(f"在目录 {input_dir} 中没有找到JSON文件")
        return
    
    print(f"找到 {len(json_files)} 个JSON文件，开始处理...")
    
    success_count = 0
    total_raw_count = 0
    total_processed_count = 0
    for json_file in json_files:
        input_path = os.path.join(input_dir, json_file)
        output_path = os.path.join(output_dir, f"{json_file}")
        
        issuccess, rawlength, processedlength = process_single_json_file(input_path, output_path)
        if issuccess:
            success_count += 1
        total_raw_count += rawlength
        total_processed_count += processedlength
    
    print(f"处理完成！成功处理 {success_count}/{len(json_files)} 个文件")
    print(f"共处理了 {total_raw_count} 条记录，成功替换 {total_processed_count} 条记录")


def extract_img_from_json(json_file_path):
    """
    从 JSON 文件中提取所有 img 字段并返回列表
    
    Args:
        json_file_path (str): JSON 文件的路径
        
    Returns:
        list: 包含所有 img 字段值的列表
    """
    try:
        # 读取 JSON 文件
        with open(json_file_path, 'r', encoding='utf-8') as file:
            data = json.load(file)
        
        # 提取所有 img 字段
        img_list = [item.get('img') for item in data if 'img' in item]
        
        # print(f'jsonfile 中共有 {len(data)} 条记录')
        # for index, item in enumerate(data):
        #     if 'img' in item:
        #         print(index, ' ', item.get('img'))

        
        return img_list
        
    except FileNotFoundError:
        print(f"错误：文件 {json_file_path} 未找到")
        return []
    except json.JSONDecodeError:
        print(f"错误：文件 {json_file_path} 不是有效的 JSON 格式")
        return []
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return []


def extract_jpg_from_txt(txt_file_path):
    """
    从 txt 文件中提取所有 .jpg 图片文件名并返回列表
    
    Args:
        txt_file_path (str): txt 文件的路径
        
    Returns:
        list: 包含所有 .jpg 文件名的列表
    """
    try:
        # 读取 txt 文件
        with open(txt_file_path, 'r', encoding='utf-8') as file:
            lines = file.readlines()
        
        # 提取所有 .jpg 文件名
        jpg_list = []
        for line in lines:
            # 使用正则表达式匹配 .jpg 文件名
            jpg_matches = re.findall(r'(\S+\.jpg)', line)
            if jpg_matches:
                jpg_list.extend(jpg_matches)
        
        return jpg_list
        
    except FileNotFoundError:
        print(f"错误：文件 {txt_file_path} 未找到")
        return []
    except Exception as e:
        print(f"读取文件时发生错误：{e}")
        return []

def find_different_elements(a, b):
    """
    找出两个列表中不同的元素（对称差集）
    
    Args:
        a (list): 第一个列表
        b (list): 第二个列表
        
    Returns:
        list: 包含所有不同元素的列表
    """
    set_a = set(a)
    set_b = set(b)
    
    # 对称差集：在a或b中，但不同时在两者中的元素
    different_elements = list(set_a ^ set_b)
    
    return different_elements

def find_duplicates_counter(lst):
    """
    使用 Counter 查找列表中的重复元素
    
    Args:
        lst (list): 输入列表
        
    Returns:
        list: 重复元素的列表
    """
    counter = Counter(lst)
    duplicates = [item for item, count in counter.items() if count > 1]
    return duplicates


def countImgNum(imgRoot):
    """
    统计目录下所有图片文件的数量（包括子目录）
    
    Args:
        imgRoot (str): 图片目录的根路径
        
    Returns:
        int: 图片文件的总数
    """
    # 定义图片文件的扩展名
    img_extensions = {'.jpg', '.jpeg', '.png', '.gif', '.bmp'}
    
    # 初始化图片数量计数器
    img_count = 0

    imgSubDir = [os.path.join(imgRoot, item) for item in os.listdir(imgRoot) if os.path.isdir(os.path.join(imgRoot, item))]

    for subDir in imgSubDir:
        files = [item for item in os.listdir(subDir) if item.endswith('.jpg')]
        img_count += len(files)
    
    return img_count



def countJsonNum(jsonRoot):
    retCount = 0
    jsonFiles = [os.path.join(jsonRoot, item) for item in os.listdir(jsonRoot) if item.endswith('.json')]
    for jsonFile in jsonFiles:
        data = read_json_file(jsonFile)
        retCount += len(data)

    return retCount


# 使用示例
if __name__ == "__main__":
    # # 示例1：基本使用
    # img_root = r"C:\Users\ZhuanZ（无密码）\Pictures\Camera Roll\English_all"
    # image_list = ["settings_2.png", "subscription.png", "subscription_2.png", "subscription_3.png"]
    # image_list = [os.path.join(img_root, item) for item in image_list]
    
    # try:
    #     # 自动布局
    #     # result = stitch_images(image_list, "output_auto.jpg")
        
    #     # 指定2x2网格
    #     result = stitch_images(image_list, os.path.join(img_root, "output_5_1x4.png"), rows=1, cols=4)
        
    #     # 垂直拼接
    #     # result = stitch_images(image_list, os.path.join(img_root, "output_1_1x4.png"), direction='vertical')
        
    #     # # 带间距的拼接
    #     # result = stitch_images(image_list, "output_spacing.jpg", spacing=10, background_color=(240, 240, 240))
        
    #     print("所有图片拼接完成！")
        
    # except Exception as e:
    #     print(f"错误: {e}")



    # 示例2：批量处理目录下的所有JSON文件,可以unicloud web控制端上传，
    # input_directory = r"C:\temp\transXiachufang\xiachufang"  # 替换为您的目录路径
    # output_directory = r"C:\temp\transXiachufang\xiachufang_processed"  # 替换为您想要的输出目录
    
    # print("\n=== 批量处理文件示例 ===")
    # process_multiple_json_files(input_directory, output_directory)

    # 示例3 对比
    # jsonfile = 'C:\\temp\\sub\\xiachufang\\8.json'
    # txtfile = 'C:\\temp\\1.txt'

    # img_list = extract_img_from_json(jsonfile)
    # img_list.sort()
    # print(f'jsonfile 中共有 {len(img_list)} 个 img 字段')
    # # print(img_list[:10])
    # jpg_list = extract_jpg_from_txt(txtfile)
    # jpg_list.sort()
    # print(f'txtfile 中共有 {len(jpg_list)} 个 .jpg 文件名')
    # # print(jpg_list[:10])
    # diff_list = find_different_elements(img_list, jpg_list)
    # print(diff_list)

    # dump_duplicates = find_duplicates_counter(img_list)
    # print(dump_duplicates)

    # 示例4：批量处理目录下的所有JSON文件,可以unicloud web控制端上传,write_json_file_bydump是格式不变，只是替换“_”为", "
    # input_directory = r"C:\temp\transXiachufang\xiachufang"  # 替换为您的目录路径
    # output_directory = r"C:\temp\transXiachufang\xiachufang_processed"  # 替换为您想要的输出目录
    
    # print("\n=== 批量处理文件示例 ===")
    # process_multiple_json_files(input_directory, output_directory)

    jsonCount = countJsonNum(r"C:\temp\sub\meishitianxia_processed")
    imgCount = countImgNum(r"C:\temp\sub\meishitianxiaEraseText")
    print(f'目录下共有 {jsonCount} 个 json 文件')
    print(f'目录下共有 {imgCount} 个图片文件')




